package eai.tp2.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Simple class to read data from the standard input/graphic windows.
 * 
 * @version 1.1 - 13 Jan 1999
 * @author Paulo Marques (pmarques@dei.uc.pt)
 */

public class User {
	// Disable default constructor
	private User() {
	}

	/**
	 * Reads an integer from the standard input. The input is terminated by a
	 * return. If the input isn't a valid number, "!!! Not an integer!!!" is
	 * displayed and the user can try to write the number again.
	 * 
	 * @return the number read
	 */
	public static int readInt() {
		while (true) {
			try {
				return Integer.valueOf(readString().trim()).intValue();
			} catch (Exception e) {
				System.out.println("!!! Not an integer !!!");
			}
		}
	}

	/**
	 * Reads a double from the standard input. The input is terminated by a
	 * return. If the input isn't a valid number, "!!! Not a double!!!" is
	 * displayed and the user can try to write the number again.
	 * 
	 * @return the number read
	 */
	public static double readDouble() {
		while (true) {
			try {
				return Double.valueOf(readString().trim()).doubleValue();
			} catch (Exception e) {
				System.out.println("!!! Not a double !!!");
			}
		}
	}

	/**
	 * Reads a float from the standard input. The input is terminated by a
	 * return. If the input isn't a valid number, "!!! Not a float!!!" is
	 * displayed and the user can try to write the number again.
	 * 
	 * @return the number read
	 */
	public static float readFloat() {
		while (true) {
			try {
				return Float.valueOf(readString().trim()).floatValue();
			} catch (Exception e) {
				System.out.println("!!! Not a float !!!");
			}
		}
	}

	/**
	 * Reads a string from the standard input. The input is terminated by a
	 * return.
	 * 
	 * @return the string read, without the final '\n\r'
	 */
	public static String readString() {
		String s = "";

		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in), 1);
			s = in.readLine();
		} catch (IOException e) {
			System.out.println("Error reading from the input stream.");
		}

		return s;
	}
}
